package com.jason.bookworm.filter;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.jason.bookworm.dao.pojo.LoginUser;
import com.jason.bookworm.dao.pojo.User;
import com.jason.bookworm.response.Result;
import com.jason.bookworm.response.StatusEnum;
import com.jason.bookworm.utils.JwtUtil;
import com.jason.bookworm.utils.RedisCache;
import com.jason.bookworm.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisCache redisCache;

    /**
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {    //如果token为空则放行
            filterChain.doFilter(request, response);//放行语句
            return;
        }
        //解析token获取用户名
        String username;
        try {
            username = jwtUtil.getUsernameFromToken(token);
        } catch (Exception e) {
            WebUtil.renderString(response, JSON.toJSONString(Result.getResult(StatusEnum.Token_Illegal)));
            return;
        }
        //从redis获取用户信息
        String redisKey = "UserInfo_" + username;
        User user = redisCache.getCacheObject(redisKey);
        if (user == null) {
            WebUtil.renderString(response, JSON.toJSONString(Result.getResult(StatusEnum.Not_Login)));
            return;
        }
        //创建LoginUser
        LoginUser loginUser = new LoginUser(user);
        //存入SecurityContextHolder
        //TODO 获取权限信息封装到authentication中
        UsernamePasswordAuthenticationToken authentication
                = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //放行
        filterChain.doFilter(request, response);
    }
}
